package com.hxx.day8;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

/**
 * 收集collect
 */
public class TestDemo7 {
    @Test
    public void test1(){
        List.of(new Book(1,"三国演义",100,"中国"),
                new Book(2,"水浒传",200,"中国"),
                new Book(3,"西游记",300,"中国"))
                .stream()
                .filter(book -> book.getPrice() > 100)
                .map(book -> book.getName())
                //.collect(Collectors.toList())
                //.collect(Collectors.toSet())
                //.collect(Collectors.toMap())
                //.collect(Collectors.toCollection(() -> new HashSet<>()));
                .collect(Collectors.toCollection(HashSet::new));
    }
    /**
     * 收集collect
     * 聚合函数的方法
     */
    @Test
    public void test2(){
        //统计价格大于100的图书数量
        Long collect = List.of(new Book(1, "三国演义", 100, "中国"),
                        new Book(2, "水浒传", 200, "中国"),
                        new Book(3, "西游记", 300, "中国"))
                .stream()
                .collect(Collectors.counting());
    }

    /**
     * 价格平均值
     */
    @Test
    public void test3(){
        //统计价格大于100的图书数量
        Double avg = List.of(new Book(1, "三国演义", 100, "中国"),
                        new Book(2, "水浒传", 200, "中国"),
                        new Book(3, "西游记", 300, "中国"))
                .stream()
                .collect(Collectors.averagingDouble(Book::getPrice));
        System.out.println(avg);
    }
    /**
     * 价格总和等
     */
    @Test
    public void test4(){
        //统计价格大于100的图书数量
        DoubleSummaryStatistics collect = List.of(new Book(1, "三国演义", 100, "中国"),
                        new Book(2, "水浒传", 200, "中国"),
                        new Book(3, "西游记", 300, "中国"))
                .stream()
                .collect(Collectors.summarizingDouble(Book::getPrice));
        System.out.println(collect.getMax());
        System.out.println(collect.getMin());
        System.out.println(collect.getSum());
        System.out.println(collect.getAverage());
    }
    /**
     * 串行流
     */
    @Test
    public void test5(){
        //消耗的时间(并行流)
        Instant start = Instant.now();
        LongStream.rangeClosed(0,1000000000L).sequential().reduce(0,Long::sum);
        Instant end = Instant.now();
        System.out.println("消耗的时间:"+ Duration.between(end,start).toMillis());
    }
    /**
     * 并行流
     */
    @Test
    public void test6(){
        //消耗的时间(并行流)
        Instant start = Instant.now();
        LongStream.rangeClosed(0,1000000000L).parallel().reduce(0,Long::sum);
        Instant end = Instant.now();
        System.out.println("消耗的时间:"+ Duration.between(end,start).toMillis());
    }
}





























